package lvbu.wang.lvbuoperator.function.nologin;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.qing.library.utils.L;

import java.util.HashMap;
import java.util.Set;

import lvbu.wang.lvbuoperator.R;
import lvbu.wang.lvbuoperator.bean.SendCommandResult;
import lvbu.wang.lvbuoperator.constants.ConstantsValue;
import lvbu.wang.lvbuoperator.core.BaseActivity;
import lvbu.wang.lvbuoperator.manager.ThreadPool;
import lvbu.wang.lvbuoperator.services.BluetoothLEService;
import lvbu.wang.lvbuoperator.utils.CommandUtils;
import lvbu.wang.lvbuoperator.utils.StringHelper;

public class NoLoginOperationActivity extends BaseActivity implements View.OnClickListener{

    private TextView mTvBluetoothConnectState;
    private Button mBtnBluetoothConnect;
    private Button mBtnClearCurrentData;
    private Button mBtnClearTotalData;

    /**
     * 广播接收器
     */
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { // 定义广播接收器，接收蓝牙消息
        @Override
        public void onReceive(Context context, final Intent intent) {

            if (intent.getAction().equals(ConstantsValue.ACTION_BLUETOOTH_CONNECT_STATE_CHANGED)) {//蓝牙状态改变
                refreshUI_bluetooth();
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_no_login_operation);
    }

    @Override
    protected void init() {

        mBtnClearCurrentData = (Button) findViewById(R.id.btn_clearCurrentData);
        mBtnClearTotalData = (Button) findViewById(R.id.btn_clearTotalData);
        mTvBluetoothConnectState = (TextView)findViewById(R.id.tv_bluetoothConnectState);
        mBtnBluetoothConnect = (Button)findViewById(R.id.btn_bluetoothConnect);
        mBtnClearCurrentData.setOnClickListener(this);
        mBtnClearTotalData.setOnClickListener(this);
        mBtnBluetoothConnect.setOnClickListener(this);
        setTitle("LVBU");
        if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_SCAN
                || getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_CONNECTING) { //正在扫描或者
            mTvBluetoothConnectState.setText("state:connecting···");
        }
        if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_CONNECTED) { //连接成功
            mTvBluetoothConnectState.setText("[state:connected]");
        }
        if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_UNCONNECT) { //未连接
            mTvBluetoothConnectState.setText("[state:unconnected]");
        }
        registerBroadcast();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_clearCurrentData:
                ThreadPool.getInstance().addTask(new Runnable() {
                    @Override
                    public void run() {

                        String commandHead = "A8";
                        String sendCode = CommandUtils.FLAG_SET + commandHead;
                        SendCommandResult scr = BluetoothLEService.sendCommandByBluetoothBle(sendCode, CommandUtils.getSetCommand(commandHead, ""));
                        if (scr.isResult()) {
                            answerProcessNewProtocol(scr.getAnswerContent());
                        } else {
                            answerErrorNewProtocol(sendCode, scr.getErrorMessage());
                        }
                    }
                });
                break;
            case R.id.btn_clearTotalData:
                ThreadPool.getInstance().addTask(new Runnable() {
                    @Override
                    public void run() {

                        String commandHead = "D6";
                        String sendCode = CommandUtils.FLAG_SET + commandHead;
                        SendCommandResult scr = BluetoothLEService.sendCommandByBluetoothBle(sendCode, CommandUtils.getSetCommand(commandHead, ""));
                        if (scr.isResult()) {
                            answerProcessNewProtocol(scr.getAnswerContent());
                        } else {
                            answerErrorNewProtocol(sendCode, scr.getErrorMessage());
                        }
                    }
                });
                break;
            case R.id.btn_bluetoothConnect:
                BluetoothLEService.connect();
                break;
        }
    }

    /**
     * 新蓝牙协议应答正确处理
     *
     * @param answerContent
     */
    private void answerProcessNewProtocol(String answerContent) {
        String flag = StringHelper.subString(answerContent, 4, 6);
        String answerResult = StringHelper.subString(answerContent, 6, 8);
        if (CommandUtils.FLAG_SET.equals(flag)) {
            String key = flag + StringHelper.subString(answerContent, 8, 10);
            String value = StringHelper.subString(answerContent, 10, answerContent.length() - 4);
            answerProcessNewProtocol(key, value, answerResult);
        } else if (CommandUtils.FLAG_GET.equals(flag)) {
            HashMap map = CommandUtils.getInquireMap(answerContent);
            Set set1 = map.keySet();
            for (Object obj : set1) {
                String key = CommandUtils.FLAG_GET + String.valueOf(obj.toString());
                String value = String.valueOf(map.get(obj));
                answerProcessNewProtocol(key, value, answerResult);
            }
        }
    }

    /**
     * 新蓝牙协议应答正确处理（单个命令）
     *
     * @param key
     * @param value
     */
    private void answerProcessNewProtocol(String key, String value, String answerResult) {
        switch (key) {

            case "0BA8":  //助力等级
                L.e("mainNewProtocol", "key = " + key + " value = " + value + " answerResult = " + answerResult);
                if ("01".equals(answerResult)) { //应答成功
                    showToastMsg("clear success");
                } else if ("02".equals(answerResult)) {
                    showToastMsg("clear fail");
                } else if ("03".equals(answerResult)) {
                    showToastMsg("invalid");
                }
                break;
            case "0BD6":  //助力等级
                L.e("mainNewProtocol", "key = " + key + " value = " + value + " answerResult = " + answerResult);
                if ("01".equals(answerResult)) { //应答成功
                    showToastMsg("clear success");
                } else if ("02".equals(answerResult)) {
                    showToastMsg("clear fail");
                } else if ("03".equals(answerResult)) {
                    showToastMsg("invalid");
                }
                break;
        }
    }

    /**
     * 新蓝牙协议应答错误处理
     *
     * @param key
     * @param errorMessage
     */
    private void answerErrorNewProtocol(String key, String errorMessage) {
        switch (key) {
            case "0BA8":
            case "0BD6":
                showToastMsg("response error" + errorMessage);
                break;
        }
    }

    /**
     * 注册广播接收器
     */
    private void registerBroadcast(){

        IntentFilter filter = new IntentFilter();
        filter.addAction(ConstantsValue.ACTION_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(ConstantsValue.ACTION_BLE_SIGNAL_STRENGTH);
        filter.addAction(ConstantsValue.ACTION_BLUETOOTH_VALUE);
        registerReceiver(broadcastReceiver, filter);
    }

    public void refreshUI_bluetooth() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_SCAN
                        || getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_CONNECTING) { //正在扫描或者
                    mTvBluetoothConnectState.setText("state:connecting···");
                }
                if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_CONNECTED) { //连接成功
                    mTvBluetoothConnectState.setText("[state:connected]");
                }
                if (getMotorDefault_bluetooth_connect_state() == BluetoothLEService.Bluetooth_UNCONNECT) { //未连接
                    mTvBluetoothConnectState.setText("[state:unconnected]");
                }
            }
        });
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        BluetoothLEService.disConnect();
        unregisterReceiver(broadcastReceiver);
    }
}
